//
//  GYDHomeViewModel.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/16.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit

class GYDHomeViewModel: NSObject {
    
    weak private var homeVC : GYDHomeViewController?
    private var tableView : UITableView?
    private var wbDataArray : [GYDWBModel]?
    private var isSince : Bool = true
    
    
    
    private lazy var titleButton : GYDTitleButton = {
        () -> GYDTitleButton in
        return GYDTitleButton(frame:CGRect(x: 0, y: 0, width: 150, height: 44))
    }()
    
    
    init(homeVC : GYDHomeViewController) {
        super.init()
        self.homeVC = homeVC
    }
    func startService() -> Void {
        let isLogin = GYDUserModel.sharedInstance.isLogin
        if isLogin {
            self.hiddenVisitorView()
        }else {
            self.showVisitorView()
        }
        GYDUserModel.sharedInstance.loginResultSignal.subscribeNext { [unowned self] (x) in
            if x as! String == LOGIN_SUCCESS {
                self.hiddenVisitorView()
            }else if x as! String == LOGINOUT_SUCCESS {
                self.showVisitorView()
            }
        }
    }
    /**
     显示登陆界面
     */
    private func showVisitorView() -> Void {
        self.setUpVisitorNavigationBar()
        let subViews = self.homeVC?.view.subviews
        for view in subViews! {
            view.removeFromSuperview()
        }
        let visitorView = GYDVisitorView(frame: self.homeVC!.view.bounds, visitorType: VisitorType.Home)
        visitorView.tag = 888
        self.homeVC?.view.addSubview(visitorView)
        visitorView.focusSignal.subscribeNext { (x) in
            print("关注")
        }
    }
    /**
     设置未登陆界面的navigationbar
     */
    private func setUpVisitorNavigationBar() -> Void {
        self.homeVC?.navigationItem.titleView = nil
        self.homeVC!.navigationItem.title = "首页"
        let loginBarItem = UIBarButtonItem(target: self, action: #selector(GYDHomeViewModel.registButtonClick), title: "注册", isLeft:true, titleColor: RGB(254, g: 118, b: 1))
        self.homeVC?.navigationItem.leftBarButtonItem = loginBarItem
        let registButton = UIBarButtonItem(target: self, action: #selector(GYDHomeViewModel.loginButtonClick), title: "登录", isLeft:false, titleColor: RGB(254, g: 118, b: 1))
        self.homeVC?.navigationItem.rightBarButtonItem = registButton
    }
    /**
     设置已经登陆的navigationbar
     */
    private func setUpNavigationBar() -> Void {
        let moneyBarItem = UIBarButtonItem(target: self, action: #selector(GYDHomeViewModel.moneyButtonClick), imageName: "redenvelope_tips_small", isLeft: true)
        self.homeVC?.navigationItem.leftBarButtonItem = moneyBarItem
        let radarBarItem = UIBarButtonItem(target: self, action: #selector(GYDHomeViewModel.radarButtonClick), imageName: "navigationbar_icon_radar", isLeft: false)
        self.homeVC?.navigationItem.rightBarButtonItem = radarBarItem
        self.titleButton.height = 44
        self.titleButton.setTitle(GYDUserModel.sharedInstance.userInfo?.screen_name, forState: UIControlState.Normal)
        self.homeVC?.navigationItem.titleView = self.titleButton
        self.titleButton.addTarget(self, action: #selector(GYDHomeViewModel.titleButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
    }
    /**
     删除未登录界面
     */
    private func hiddenVisitorView() -> Void {
        self.setUpNavigationBar()
        let subViews = self.homeVC?.view.subviews
        for view in subViews! {
            view.removeFromSuperview()
        }
        showWBView()
    }
    /**
     钱包按钮点击
     */
    @objc private func moneyButtonClick() -> Void {
        
    }
    /**
     扫描按钮点击、
     */
    @objc private func radarButtonClick() -> Void {
        let popVC = GYDPopViewController(frame:CGRect(x: GYDWindowWidth - 150 - 8, y: 55, width: 150, height: 100))
        popVC.popType = PopType.PopRight
        popVC.dataSoureType = PopDataSoureType.TitleAndImage
        popVC.dataSoure = [["imageName":"popover_icon_radar","title":"雷达"],["imageName":"popover_icon_qrcode","title":"扫一扫"]]
        popVC.popSelectedBlock = { (index : Int) -> Void in
            if index == 1 {
                let scanVC = GYDScanViewController()
                self.homeVC?.navigationController?.pushViewController(scanVC, animated: true)
            }
        }
        self.homeVC?.presentViewController(popVC, animated: true, completion: nil)
    }
    
    @objc func loginButtonClick() -> Void {
        print("登陆按钮点击")
        self.gotoLogin()
    }
    @objc func registButtonClick() -> Void {
        print("注册按钮点击")
        self.gotoLogin()
    }
    /**
     区登录
     */
    func gotoLogin() -> Void {
        let loginVC = GYDLoginViewController()
        self.homeVC?.presentViewController(loginVC, animated: true, completion: nil)
    }
    
    @objc private func titleButtonClick() -> Void {
        self.titleButton.selected = !self.titleButton.selected
        let popVC = GYDPopViewController(frame: CGRect(x: GYDWindowWidth/2.0 - 100, y: 55, width: 200, height: 300))
        popVC.dissmissBlock = { () -> Void in
            self.titleButton.selected = !self.titleButton.selected
        }
        popVC.popType = PopType.PopCenter
        popVC.selectedIdex = 0
        popVC.dataSoureType = PopDataSoureType.OnlyHome
        popVC.dataSoure = ["首页","好友圈❤️","群微博","特别关注","名人明星","同学","同事","悄悄关注","周边微博"]
        self.homeVC?.presentViewController(popVC, animated: false, completion: nil)
    }
    
}

// MARK: - 微博业务处理
extension GYDHomeViewModel : UITableViewDelegate, UITableViewDataSource{
    func showWBView() {
        let tableView = UITableView(frame: self.homeVC!.view.bounds, style: UITableViewStyle.Plain)
        tableView.backgroundColor = BASECOLOR
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 250
        tableView.registerClass(GYDHomeWBTableViewCell.classForCoder(), forCellReuseIdentifier: "cellId")
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        self.homeVC?.view.addSubview(tableView)
        self.tableView = tableView
        let refreshHeader = GYDRefreshHeader { [unowned self] in
            self.isSince = true
            self.requestWBDataFromNet()
        }
        refreshHeader.showMusic = true
        refreshHeader.settingParameter()
        tableView.mj_header = refreshHeader
        
        let freshFooter = GYDRefreshFooter(refreshingBlock: {
            self.isSince = false
            self.requestWBDataFromNet()
        })
        freshFooter.settingParameter()
        self.tableView?.mj_footer = freshFooter
        requestWBDataFromNet()
    }
    
    
    
    func requestWBDataFromNet() {
        if GYDUserModel.sharedInstance.access_token == nil {
            return
        }
        var parames : [String : NSObject] = ["access_token":GYDUserModel.sharedInstance.access_token!]
        if self.wbDataArray == nil {
            parames["page"] = 1
        }else {
            if self.isSince == true {
                if self.wbDataArray != nil {
                    if let topWBModel : GYDWBModel = self.wbDataArray?.first {
                        parames["since_id"] = topWBModel.id
                        parames["max_id"] = 0
                    }
                }else {
                    parames["since_id"] = 0
                    parames["max_id"] = 0
                }
            }else {
                if self.wbDataArray != nil {
                    if let topWBModel : GYDWBModel = self.wbDataArray?.last  {
                        parames["max_id"] = topWBModel.id - 1
                        parames["since_id"] = 0
                    }
                }
            }
        }
        GYDNetWorkTools.shareInstance.httpGetWithUrl("https://api.weibo.com/2/statuses/friends_timeline.json", parames: parames, successBlock: { [unowned self](result) in
            print(result)
            self.tableView?.mj_footer.endRefreshing()
            self.tableView?.mj_header.endRefreshing()
            if result == nil {
                return
            }
            guard let dataSoure : NSDictionary = result as? NSDictionary else {
                return
            }
            let tempArray = NSArray.yy_modelArrayWithClass(GYDWBModel.classForCoder(), json: dataSoure.objectForKey("statuses")!)
            if tempArray?.count == 0 {
                return
            }
            var array = [GYDWBModel]()
            for model in tempArray! {
                array.append(model as! GYDWBModel)
            }
            if self.isSince == true {
                if self.wbDataArray == nil {
                    self.wbDataArray = [GYDWBModel]()
                }
                self.wbDataArray = array + self.wbDataArray!
                playMusic("msgcome")
                if let messageNumber : Int = array.count {
                    GYDMessgeSendView.showInView((self.homeVC?.view)!, messageNumber: messageNumber)
                }
            }else {
                self.wbDataArray = self.wbDataArray! + array
            }
            //缓存图片
            GYDWBModel.cacheImageArray(array, completeBlock: {
                self.tableView?.reloadData()
            })
            }) { (error) in
               print(error)
                self.tableView?.mj_footer.endRefreshing()
                self.tableView?.mj_header.endRefreshing()
        }
    }
    
    
    // MARK: - UITableViewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.wbDataArray?.count ?? 0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cellId", forIndexPath: indexPath)
        guard let model : GYDWBModel = wbDataArray![indexPath.row] else {
            return cell
        }
        guard let wbCell = cell as? GYDHomeWBTableViewCell else {
            return cell
        }
        wbCell.updateDataWithWBModel(model)
        
        wbCell.shareButton?.rac_signalForControlEvents(UIControlEvents.TouchUpInside).takeUntil(wbCell.rac_prepareForReuseSignal).subscribeNext({ (x) in
            print("分享按钮点击")
        })
        
        wbCell.commentsButton?.rac_signalForControlEvents(UIControlEvents.TouchUpInside).takeUntil(wbCell.rac_prepareForReuseSignal).subscribeNext({ (x) in
            print("评论按钮点击")
        })
        wbCell.hitsButton?.rac_signalForControlEvents(UIControlEvents.TouchUpInside).takeUntil(wbCell.rac_prepareForReuseSignal).subscribeNext({ (x) in
            print("点赞按钮点击")
        })
        wbCell.downButton?.rac_signalForControlEvents(UIControlEvents.TouchUpInside).takeUntil(wbCell.rac_prepareForReuseSignal).subscribeNext({ (x) in
            GYDBottomPopView.showWithTitleArray(["收藏","帮上头条","取消关注","屏蔽","举报"], selectedBlock: { (index) in
                print(index)
                }, dissmissBlock: nil)
        })
        wbCell.imageSignal.takeUntil(wbCell.rac_prepareForReuseSignal).subscribeNext { (x) in
            guard let picDic : [String : NSObject] = x as? [String : NSObject] else {
                return
            }
            let imagePickerVC = GYDImagePickerViewController()
            imagePickerVC.selectedIndex = picDic[SELECTEDINDEX] as! Int
            imagePickerVC.allImageUrl = picDic[ALLIMAGEURL] as? [String]
            imagePickerVC.cellFrameDic = picDic[CELLFRAMEDIC] as? [Int:NSValue]
            imagePickerVC.imageSize = picDic[CELLIMAGESIZE] as? [Int:NSValue]
            self.homeVC!.presentViewController(imagePickerVC, animated: false, completion: nil)
        }
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        let model : GYDWBModel = wbDataArray![indexPath.row]
        if model.cellHeight == 0 {
            let rowHeight = GYDHomeWBTableViewCell.calculateRowHeight(model)
            model.cellHeight = rowHeight
            return rowHeight
        }else {
            return model.cellHeight
        }
    }
    
}



